<?php
/**
 * Created by 常志明.
 * User: Administrator
 * Date: 2018-08-16
 * Time: 17:52
 * 能耗统计  表：  merchant商户  meter电表
 */

namespace app\index\controller;
use think\Controller;
use think\File;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style;

class EnergyReadMeter extends Controller
{
    //抄表计划
    const energy_read_plan = [
        'parentId'   =>'',      //门店id  storemanage
        'datetime'   =>'',      //创建时间
        'modtime'    =>'',      //修改时间
        'allMeterNum'=>'0',     //表总数
        'completeNum'=>'0',     //完成数量
        'planName'   =>'',      //抄表计划名称

        'waterTotal' =>'0',     //水总量
        'waterMoney' =>'0',     //金额
        'waterNote'  =>'',      //水表备注
        'amTotal'    =>'0',     //电总量
        'amMoney'    =>'0',     //金额
        'amNote'     =>'',      //电表备注
        'gasTotal'   =>'0',     //燃气总量
        'gasMoney'   =>'0',     //金额
        'gasNote'    =>'',      //燃气表备注
        'total'     => false,   //是否是总量录入
    ];
    //详细设备表度数
    const energy_meternums = [
        'parentId'=>'',          //抄表计划id energy_read_plan
        'shopId'  =>'',          //商户id
        'ammeterreadNum'=>'0',   //电表度数
        'waterreadNum'=>'0',     //水表度数
        'gasreadNum'=>'0',       //燃气表读数
        'people'=>'',            //抄表人
        'modtime'=>'',           //抄表时间
    ];

    public static function getData($where, $one = true, $table = 'energy_read_plan')
    {
        return ($one == true) ? getFirst(mongo($table)->where($where)->select()) : mongo($table)->where($where)->select();
    }
    public static function setData($where, $data, $table = 'energy_read_plan')
    {
        mongo($table)->where($where)->update($data);
    }
    public static function insertData($data, $table = 'energy_read_plan')
    {
        mongo($table)->insert($data);
        return mongo($table)->getLastInsID();
    }
    public static function deleteData($where, $table = 'energy_read_plan')
    {
        mongo($table)->where($where)->delete();
    }

    /**
     * 新建抄表计划
     * @param array $shopIds           商户id
     * @return array
     */
    public static function newMeterReadPlan($shopIds = [])
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $shopIds   = input('shopIds/a', []);
        $storeId = User::getStoreId();
        $insertdata = [
            'parentId'    =>$storeId,            //门店
            'planName'    =>date('Y-m-d-h:i:s').'-抄表计划',
            'allMeterNum' =>count($shopIds),
            'datetime'    =>date('Y-m-d'),
            'modtime'     =>date('Y-m-d'),
        ];

        $readPlanId = self::insertData(array_merge(self::energy_read_plan, $insertdata));//抄表计划id //添加抄表计划

        foreach ($shopIds as $shopId) {
            $insertdata = [
                'parentId'=> $readPlanId,
                'shopId'  => $shopId,
            ];
            self::insertData(array_merge(self::energy_meternums, $insertdata));//添加每个商户表
        }
        return RD(SUCCESS, ['planId'=>$readPlanId, 'datetime'=>date('Y-m-d'), 'planName'=>date('Y-m-d').'-抄表计划']);
    }
    /**
     * 编辑抄表计划名称
     * @param string $planId    抄表计划id
     * @param string $planName  抄表计划名称
     * @return array
     */
    public static function editMeterReadPlan($planId = null, $planName = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $planId   = input('planId');
        $planName = input('planName');
        self::setData(['id'=>$planId], ['planName'=>$planName]);

        return RD(SUCCESS);
    }

    /**
     *  删除抄表计划
     * @param string $planId 抄表计划id
     * @return array
     */
    public static function deleteMeterReadPlan($planId = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $planId = empty($planId) ? input('planId') : $planId;

        self::deleteData(['id'=>$planId]);
        $childs = self::getData(['parentId'=>$planId], false);
        foreach ($childs as $child) {
            self::deleteData(['id' => $child['id']]);  //删除子项
        }
        return RD(SUCCESS);
    }

    /**
     * 获取所有抄表计划
     * @param string $datetime  创建时间
     * @return array
     */
    public static function getMeterReadPlan($datetime = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $datetime =  input('datetime');  //创建时间  年-月 2018-09
        $storeId   = User::getStoreId();

        $data = self::getData(['parentId'=>$storeId, 'datetime'=>['like', $datetime.'.*']], false);

        //改变id
        for($x = 0; $x < count($data); $x++)
        {
            renameArray($data[$x], 'id', 'planId');
        }
//        //排序
//        $my_sort = function ($a, $b) {
//
//            switch ($a['state']) {
//                case '开始':
//                    $avalue = 3;
//                    break;
//                case '进行中':
//                    $avalue = 2;
//                    break;
//                case '完成':
//                    $avalue = 1;
//                    break;
//            }
//            switch ($b['state']) {
//                case '开始':
//                    $bvalue = 3;
//                    break;
//                case '进行中':
//                    $bvalue = 2;
//                    break;
//                case '完成':
//                    $bvalue = 1;
//                    break;
//            }
//            if ($avalue == $bvalue)
//                return 0;
//            return ($avalue < $bvalue)? 1: -1;
//        };
//        usort($data, $my_sort);  //排序

        return RD(SUCCESS, $data);
    }
    /**
     * 根据抄表计划获取所有商户表信息
     * @param string $planId        抄表计划id
     * @param string $keyword       店铺名模糊搜索
     * @return array
     */
    public static function getMeterNum($planId = null,  $keyword = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $planId      = input('planId');
        $keyword     = input('keyword', '');

        $shops = EnergyStore::getData(['floor|shopName'=>['like', '.*'.$keyword.'.*']], false);

        $returnData = [];
        $data = self::getData(['parentId'=>$planId], false);

        foreach ($data as $key=>$value) {
            foreach ($shops as $shop) {
                if($value['shopId'] == $shop['id']) {
                    DArray($shop, 'id');
                    DArray($value, 'shopId');
                    array_push($returnData, array_merge($value, $shop));
                    break;
                }
            }
        }
        return RD(SUCCESS, ['total'=>count($data),  'stores'=>$returnData]);
    }

    /**
     * 写入抄表度数
     * @param string $id               商户抄表id  getMeterNum获取 商户抄表id
     * @param string $waterreadNum     水表读数
     * @param string $ammeterreadNum   电表读数
     * @param string $gasreadNum       燃气表读数
     * @param string $people           抄表人
     * @return array
     */
    public static function writeMeterNum($id = null, $waterreadNum = null, $ammeterreadNum = null, $gasreadNum = null, $people = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id     = input('id');
        $waterreadNum    = input('waterreadNum');
        $ammeterreadNum  = input('ammeterreadNum');
        $gasreadNum      = input('gasreadNum');
        $people          = input('people');

        $meterRead = self::getData(['id'=>$id]);
        $meterPlan = self::getData(['id'=>$meterRead['parentId']]);

        if(empty($meterRead['people'])) {
            $completeNum = $meterPlan['completeNum'] + 1;
            self::setData(['id'=>$meterRead['parentId']], ['completeNum'=>$completeNum, 'modtime' =>date('Y-m-d')]);
        }
        $updateData = [
            'waterreadNum'  =>$waterreadNum,
            'ammeterreadNum'=>$ammeterreadNum,
            'gasreadNum'    =>$gasreadNum,
            'people'        =>$people,
            'modtime'       =>date('Y-m-d'),
        ];
        self::setData(['id'=>$id], $updateData);
        return RD(SUCCESS);
    }
    /**
     * 录入编辑总量详细信息 总量数
     * @param string $id           总量录入id
     * @param string $energyType   能耗类型（水/电/燃气）
     * @param string $allTotal     总共消耗量
     * @param string $money        购买金额
     * @param string $note         备注信息
     * @return array
     */
    public static function editTotalDetail($id = null, $energyType = null, $allTotal = null, $money = null, $note = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;
        $id          = input('id');
        $energyType  = input('energyType');
        $allTotal    = input('allTotal');
        $money       = input('money');
        $note        = input('note');

        $insertData = [];
        switch ($energyType)
        {
            case '水':
                $insertData = ['waterTotal'=>$allTotal, 'waterMoney'=>$money, 'waterNote'=>$note];
                break;
            case '电':
                $insertData = ['amTotal'=>$allTotal, 'amMoney'=>$money, 'amNote'=>$note];
                break;
            case '燃气':
                $insertData = ['gasTotal'=>$allTotal, 'gasMoney'=>$money, 'gasNote'=>$note];
                break;
        }
        self::setData(['id'=>$id], array_merge($insertData, ['total' => true]));
        return RD(SUCCESS);
    }

    /**
     * 获取总量详细信息
     * @param string $id   总量录入id
     * @return array
     */
    public static function getTotalDetail($id = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $id = input('id');
        if(empty($id)) return RD(PARA_NOT_NULL);

        $marketWaterAll = 0;
        $marketamAll    = 0;
        $marketgasAll   = 0;
        $shopWaterAll   = 0;
        $shopamAll      = 0;
        $shopgasAll     = 0;
        //获取所有电表
        $meters = self::getData(['parentId' => $id], false);
        foreach ($meters as $meter) {
            $tData = EnergyStore::getData(['id'=>$meter['shopId']]);
            if(empty($tData)) {
                continue;
            }
            if(strstr($tData['storeName'], '超市') != false) {
                $marketWaterAll += $meter['waterreadNum'];
                $marketamAll    += $meter['ammeterreadNum'];
                $marketgasAll   += $meter['gasreadNum'];
            } else {
                $shopWaterAll += $meter['waterreadNum'];
                $shopamAll    += $meter['ammeterreadNum'];
                $shopgasAll   += $meter['gasreadNum'];
            }
        }

        $result = self::getData(['id'=>$id]);
        //水
        $unitPrice = $result['waterTotal'] > 0 ? round($result['waterMoney'] / $result['waterTotal'], 2) : '0';
        $water = [
            'energyType'   =>'水',
            'allTotal'     =>$result['waterTotal'],
            'publicTotal'  =>($result['waterTotal'] - $marketWaterAll - $shopWaterAll),
            'tenantTotal'  =>$marketWaterAll,
            'shopTotal'    =>$shopWaterAll,
            'money'        =>$result['waterMoney'],
            'unitPrice'    =>$unitPrice,
            'note'         =>$result['waterNote'],
        ];
        //电
        $unitPrice = $result['amTotal'] > 0 ? round($result['amMoney']/ $result['amTotal'], 2) : '0';
        $am = [
            'energyType'   =>'电',
            'allTotal'     =>$result['amTotal'],
            'publicTotal'  =>($result['amTotal'] - $marketamAll - $shopamAll),
            'tenantTotal'  =>$marketamAll,
            'shopTotal'    =>$shopamAll,
            'money'        =>$result['amMoney'],
            'unitPrice'    =>$unitPrice,
            'note'         =>$result['amNote']
        ];
        //燃气
        $unitPrice = $result['gasTotal'] > 0 ? round($result['gasMoney']/ $result['gasTotal'], 2) : '0';
        $gas = [
            'energyType'   =>'燃气',
            'allTotal'     =>$result['gasTotal'],
            'publicTotal'  =>($result['gasTotal'] - $marketgasAll - $shopgasAll),
            'tenantTotal'  =>$marketgasAll,
            'shopTotal'    =>$shopgasAll,
            'money'        =>$result['gasMoney'],
            'unitPrice'    =>$unitPrice,
            'note'         =>$result['gasNote']
        ];
        return RD(SUCCESS, [$water, $am, $gas]);
    }
    /**
     * 根据年/月获取能耗情况
     * @param string $date  年或月统计（2018、2018-05）
     * @return array
     */
    public static function getEnergyDetailByDate($date = null)
    {
        if(!empty($perssion = perssion([LOGIN, SHOP])))   //权限判断
            return $perssion;

        $date    = input('date');
        $storeId = User::getStoreId();
        $results = self::getData(['parentId'=>$storeId, 'createTime'=>['like', $date.'.*'], 'total'=>true], false);
        $publicTotal = 0;    $tenantTotal = 0;   $shopTotal = 0;
        foreach ($results as $result)
        {
            $marketWaterAll = 0;
            $marketamAll    = 0;
            $marketgasAll   = 0;
            $shopWaterAll   = 0;
            $shopamAll      = 0;
            $shopgasAll     = 0;
            $id = $result['id'];
            //获取所有电表
            $meters = self::getData(['parentId' => $id], false);
            foreach ($meters as $meter) {
                $tData = EnergyStore::getData(['id'=>$meter['shopId']]);
                if(strstr($tData['storeName'], '超市') != false) {
                    $marketWaterAll += $meter['waterreadNum'];
                    $marketamAll    += $meter['ammeterreadNum'];
                    $marketgasAll   += $meter['gasreadNum'];
                } else {
                    $shopWaterAll += $meter['waterreadNum'];
                    $shopamAll    += $meter['ammeterreadNum'];
                    $shopgasAll   += $meter['gasreadNum'];
                }
            }

            //水
            $unitPrice   = $result['waterTotal'] > 0 ? round($result['waterMoney'] / $result['waterTotal'], 2) : '0';
            $publicTotal += ($result['waterTotal'] - $marketWaterAll - $shopWaterAll) * $unitPrice;  //公区
            $tenantTotal += $marketWaterAll * $unitPrice;  //超市
            $shopTotal   += $shopWaterAll   * $unitPrice;     //商户
            //电
            $unitPrice    = $result['amTotal'] > 0 ? round($result['amMoney']/ $result['amTotal'], 2) : '0';
            $publicTotal += ($result['amTotal'] - $marketamAll - $shopamAll) * $unitPrice;  //公区
            $tenantTotal += $marketamAll * $unitPrice;  //超市
            $shopTotal   += $shopamAll * $unitPrice;     //商户
            //燃气
            $unitPrice   = $result['gasTotal'] > 0 ? round($result['gasMoney']/ $result['gasTotal'], 2) : '0';
            $publicTotal += ($result['gasTotal'] - $marketgasAll - $shopgasAll) * $unitPrice;  //公区
            $tenantTotal += $marketgasAll * $unitPrice;  //超市
            $shopTotal   += $shopgasAll * $unitPrice;     //商户
        }

        if(strlen($date) > 4) { //上一个月
            $datetime = date_create_from_format("Y-m", $date);
            date_sub($datetime, date_interval_create_from_date_string("1 month"));
            $date = date_format($datetime,"Y-m");
        } else {               //上一年
            $datetime = date_create_from_format("Y", $date);
            date_sub($datetime, date_interval_create_from_date_string("1 year"));
            $date = date_format($datetime,"Y");
        }
        //上一年/一个月
        $results = self::getData(['parentId'=>$storeId, 'createTime'=>['like', $date.'.*'], 'total'=>true], false);   //查询该时间所有总量录入  //本月
        $publicTotalpre = 0;    $tenantTotalpre = 0;   $shopTotalpre = 0;

        foreach ($results as $result)
        {
            $marketWaterAll = 0;
            $marketamAll    = 0;
            $marketgasAll   = 0;
            $shopWaterAll   = 0;
            $shopamAll      = 0;
            $shopgasAll     = 0;
            $id = $result['id'];
            //获取所有电表
            $meters = self::getData(['parentId' => $id], false);
            foreach ($meters as $meter) {
                $tData = EnergyStore::getData(['id'=>$meter['shopId']]);
                if(strstr($tData['storeName'], '超市') != false) {
                    $marketWaterAll += $meter['waterreadNum'];
                    $marketamAll    += $meter['ammeterreadNum'];
                    $marketgasAll   += $meter['gasreadNum'];
                } else {
                    $shopWaterAll += $meter['waterreadNum'];
                    $shopamAll    += $meter['ammeterreadNum'];
                    $shopgasAll   += $meter['gasreadNum'];
                }
            }

            //水
            $unitPrice      = $result['waterTotal'] > 0 ? round($result['waterMoney'] / $result['waterTotal'], 2) : '0';
            $publicTotalpre += ($result['waterTotal'] - $marketWaterAll - $shopWaterAll) * $unitPrice;  //公区
            $tenantTotalpre += $marketWaterAll * $unitPrice;  //超市
            $shopTotalpre   += $shopWaterAll * $unitPrice;     //商户
            //电
            $unitPrice      = $result['amTotal'] > 0 ? round($result['amMoney']/ $result['amTotal'], 2) : '0';
            $publicTotalpre += ($result['amTotal'] - $marketamAll - $shopamAll) * $unitPrice;  //公区
            $tenantTotalpre += $marketamAll * $unitPrice;  //超市
            $shopTotalpre   += $shopamAll * $unitPrice;     //商户
            //燃气
            $unitPrice      = $result['gasTotal'] > 0 ? round($result['gasMoney']/ $result['gasTotal'], 2) : '0';
            $publicTotalpre += ($result['gasTotal'] - $marketgasAll - $shopgasAll) * $unitPrice;  //公区
            $tenantTotalpre += $marketgasAll * $unitPrice;  //超市
            $shopTotalpre   += $shopgasAll * $unitPrice;     //商户
        }
        $storeTotal  = ['energyType'=>'商户', 'money'=>$shopTotal, 'preMoney'=>$shopTotalpre, 'HuanBiCha'=>'0', 'HuanBiScale'=>'0', 'TongBiCha'=>'0', 'TongBiScale'=>'0'];
        $tenantTotal = ['energyType'=>'超市', 'money'=>$tenantTotal, 'preMoney'=>$tenantTotalpre, 'HuanBiCha'=>'0', 'HuanBiScale'=>'0', 'TongBiCha'=>'0', 'TongBiScale'=>'0'];
        $publicTotal = ['energyType'=>'公区', 'money'=>$publicTotal, 'preMoney'=>$publicTotalpre, 'HuanBiCha'=>'0', 'HuanBiScale'=>'0', 'TongBiCha'=>'0', 'TongBiScale'=>'0'];

        return RD(SUCCESS, [$storeTotal, $tenantTotal, $publicTotal]);
    }
    //删除数据根据门店id
    public static function deleteByStore($storeId)
    {
        self::deleteData(['parentId'=>$storeId]);
        $childs = self::getData(['parentId'=>$storeId], false);
        foreach ($childs as $child) {
            self::deleteByStore($child['id']);  //删除子项
        }
    }
    /** 多文件导出
     * @param array $ids 抄表计划id
     * @return array
     */
    public static function multiexportReportEnergy($ids = [])
    {
        if(!empty($perssion = perssion([LOGIN, SHOP]))) { return RD(NO_LOGIN);}  //权限判断
        $ids = input('ids/a', []);
        $ids = json_decode($ids[0] ?? '');
        $filenames = [];
        foreach ($ids as $id) {
            $filename = self::exportReportEnergy($id);
            array_push($filenames, $filename);
        }

        $zipName = '抄表批量下载.zip';
        $zip = new \ZipArchive;//使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
        if ($zip->open($zipName, \ZIPARCHIVE::OVERWRITE | \ZIPARCHIVE::CREATE)!==TRUE) {
            return RD(FAIL, '无法打开文件，或者文件创建失败');
        }
        foreach ($filenames as $filename) {
            if(file_exists($filename)){
                $zip->addFile($filename, $filename);//第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
            }
        }
        $zip->close();
        foreach ($filenames as $filename) {
            @unlink($filename);
        }
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=".$zipName);
        readfile($zipName);
        @unlink($zipName);
    }


    /** 导出一个抄表
     * @param string $id 抄表计划id
     * @return array
     */
    public static function oneexportReportEnergy($id = '')
    {
        if(!empty($perssion = perssion([LOGIN, SHOP]))) { return RD(NO_LOGIN);}  //权限判断
        $id = input('id');
        if(empty($id)) {
            return RD(PARA_NOT_NULL);
        }
        $filename = self::exportReportEnergy($id);
        header("Content-Type: application/force-download");
        header("Content-Disposition: attachment; filename=".$filename);
        readfile($filename);
        @unlink($filename);
    }
    /** 导出一个作业指导书
     * @param string $id 抄表计划id
     * @return 文件路径
     */
    public static function exportReportEnergy($id)
    {
        $readMeterPlan = self::getData(['id'=>$id]);
        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();

        $worksheet->setTitle('抄表');

        $worksheet->getColumnDimension('A')->setWidth(20);
        $worksheet->getColumnDimension('B')->setWidth(20);
        $worksheet->getColumnDimension('C')->setWidth(20);
        $worksheet->getColumnDimension('D')->setWidth(20);
        $worksheet->getColumnDimension('E')->setWidth(20);

        $currentIndex = 1;
        $worksheet->mergeCellsByColumnAndRow(1, $currentIndex, 4, $currentIndex);
        $worksheet->getStyleByColumnAndRow(1, $currentIndex)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER_CONTINUOUS);
        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, ($readMeterPlan['datetime'] ?? '').'抄表');
        $currentIndex++;

        $worksheet->setCellValueByColumnAndRow(1, $currentIndex, '楼层');
        $worksheet->setCellValueByColumnAndRow(2, $currentIndex, '商铺');
        $worksheet->setCellValueByColumnAndRow(3, $currentIndex, '水表数');
        $worksheet->setCellValueByColumnAndRow(4, $currentIndex, '电表数');
        $worksheet->setCellValueByColumnAndRow(5, $currentIndex, '燃气数');
        $currentIndex++;

        //获取所有电表
        $meters = self::getData(['parentId' => $id], false);

        foreach ($meters as $meter) {
            $tData = EnergyStore::getData(['id'=>$meter['shopId']]);
            $worksheet->setCellValueByColumnAndRow(1, $currentIndex, $tData['floor'] ?? '');
            $worksheet->setCellValueByColumnAndRow(2, $currentIndex, $tData['storeName'] ?? '');
            $worksheet->setCellValueByColumnAndRow(3, $currentIndex, $meter['waterreadNum'] ?? '');
            $worksheet->setCellValueByColumnAndRow(4, $currentIndex, $meter['ammeterreadNum'] ?? '');
            $worksheet->setCellValueByColumnAndRow(5, $currentIndex, $meter['gasreadNum'] ?? '');
            $currentIndex++;
        }

        $writer = new Xls($spreadsheet);
        $filename = $readMeterPlan['planName'].'--.xls';
        $writer->save($filename);
        return $filename;
    }
}
